package com.ias.agdis_r.activity.setting;

import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.provider.Settings;
import android.text.Editable;
import android.text.InputType;
import android.text.Selection;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.ias.agdis_r.R;
import com.ias.agdis_r.activity.BaseKeyActivity;
import com.ias.agdis_r.manager.DataBaseManager;
import com.ias.agdis_r.manager.EffectManager;
import com.ias.agdis_r.module.ParameterModel;
import com.ias.agdis_r.util.S;

/**
 * GPS设置界面
 * @author guoxr
 *
 */
public class GPSSettingActivity extends BaseKeyActivity implements OnClickListener {
	private ActionBar actionBar;
	private TextView edit_gpsstate;
	private EditText txt_maxspeeding; // 最大速度
	private EditText txt_minspeeding; // 最小速度
	private EditText txt_collect_interval; // 采集GPS数据间隔
	private EditText txt_send_interval; // 发送GPS数据间隔
	private LinearLayout btn_sys;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_gpssetting);
		initView();
	}

	private void initView() {
		// TODO Auto-generated method stub
		actionBar = getActionBar();
		initActionBar();
		edit_gpsstate = (TextView) findViewById(R.id.edit_gpsstate);
		btn_sys = (LinearLayout) findViewById(R.id.layout_gpssys);
		btn_sys.setOnClickListener(this);
		txt_maxspeeding = (EditText) findViewById(R.id.edit_speedMax);
		txt_minspeeding = (EditText) findViewById(R.id.edit_speedMin);
		txt_collect_interval = (EditText) findViewById(R.id.edit_collect);
		txt_send_interval = (EditText) findViewById(R.id.edit_send);
		showInfo();
		setTextChangedListener(txt_maxspeeding, InputType.TYPE_CLASS_NUMBER
				| InputType.TYPE_NUMBER_FLAG_SIGNED, "1234567890");
		setTextChangedListener(txt_minspeeding, InputType.TYPE_CLASS_NUMBER
				| InputType.TYPE_NUMBER_FLAG_SIGNED, "1234567890");
		setTextChangedListener(
				txt_collect_interval,
				InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_SIGNED,
				"1234567890");
		setTextChangedListener(txt_send_interval, InputType.TYPE_CLASS_NUMBER
				| InputType.TYPE_NUMBER_FLAG_SIGNED, "1234567890");
	}

	private void setTextChangedListener(final EditText view, final int type,
			final String digits) {
		if (view != null) {
			view.addTextChangedListener(new TextWatcher() {
				String tmp = "";

				@Override
				public void onTextChanged(CharSequence s, int start,
						int before, int count) {
					// TODO Auto-generated method stub
				}

				@Override
				public void beforeTextChanged(CharSequence s, int start,
						int count, int after) {
					tmp = s.toString();
				}

				@Override
				public void afterTextChanged(Editable s) {
					// view.setInputType(type);

					// 下面两行代码实现: 输入框光标一直在输入文本后面
					Editable etable = view.getText();
					Selection.setSelection(etable, etable.length());
					String str = s.toString();
					if (str.equals(tmp)) {
						return;
					}
					StringBuffer sb = new StringBuffer();
					for (int i = 0; i < str.length(); i++) {
						if (S.isNotEmpty(digits)) {
							if (digits.indexOf(str.charAt(i)) >= 0) {
								sb.append(str.charAt(i));
							}
						} else {
							sb.append(str.charAt(i));
						}
					}
					tmp = sb.toString();
					view.setInputType(type);
					view.setText(tmp);
				}
			});
		}
	}

	/**
	 * 绑定数据
	 * 
	 */
	private void showInfo() {
		String maxSpeed = DataBaseManager.getInstance().getString(
				ParameterModel.T_GPS_INFO, ParameterModel.MAXSPEEDING);
		String minSpeed = DataBaseManager.getInstance().getString(
				ParameterModel.T_GPS_INFO, ParameterModel.MINSPEEDING);
		String collectInterval = DataBaseManager.getInstance().getString(
				ParameterModel.T_GPS_INFO, ParameterModel.COLLECT_INTERVAL);
		String sendInterval = DataBaseManager.getInstance().getString(
				ParameterModel.T_GPS_INFO, ParameterModel.SEND_INTERVAL);
		if (isGPSEnable()) {
			edit_gpsstate.setText(R.string.gps_state_on);
		} else {
			edit_gpsstate.setText(R.string.gps_state_off);
		}
		txt_maxspeeding.setText(maxSpeed);
		txt_minspeeding.setText(minSpeed);
		txt_collect_interval.setText(collectInterval);
		txt_send_interval.setText(sendInterval);
	}

	private void initActionBar() {
		actionBar.setCustomView(LayoutInflater.from(GPSSettingActivity.this)
				.inflate(R.layout.actionbar_settings, null));
		actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
		actionBar.setDisplayShowCustomEnabled(true);
		TextView title = (TextView) findViewById(R.id.txt_title);
		title.setText(R.string.GPSSettingActivity);
		ImageView back = (ImageView) findViewById(R.id.actionbar_settings_back);
		back.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();
			}
		});
	}

	private boolean save() {
		// TODO Auto-generated method stub
		try {
			String maxspeeding = txt_maxspeeding.getText().toString();
			String minspeeding = txt_minspeeding.getText().toString();
			String collectInterval = txt_collect_interval.getText().toString();
			String sendInterval = txt_send_interval.getText().toString();
			if (S.isEmpty(maxspeeding)) {
				EffectManager.getInstance().ttsPlay(
						EffectManager.TTS_TYPE_UPTO,
						getString(R.string.maxSpeeding) + getString(R.string.check_input_error), false);
				return false;
			} else if (S.isEmpty(minspeeding)) {
				EffectManager.getInstance().ttsPlay(
						EffectManager.TTS_TYPE_UPTO,
						getString(R.string.minSpeeding) + getString(R.string.check_input_error), false);
				return false;
			} else if (S.isEmpty(collectInterval)) {
				EffectManager.getInstance().ttsPlay(
						EffectManager.TTS_TYPE_UPTO,
						getString(R.string.collectInterval) + getString(R.string.check_input_error), false);
				return false;
			} else if (S.isEmpty(sendInterval)) {
				EffectManager.getInstance().ttsPlay(
						EffectManager.TTS_TYPE_UPTO,
						getString(R.string.sendInterval) + getString(R.string.check_input_error), false);
				return false;
			} else if (!S.isJobNumber(maxspeeding)) {
				EffectManager.getInstance().ttsPlay(
						EffectManager.TTS_TYPE_UPTO,
						getString(R.string.maxSpeeding) + getString(R.string.check_input_legal), false);
				return false;
			} else if (!S.isJobNumber(minspeeding)) {
				EffectManager.getInstance().ttsPlay(
						EffectManager.TTS_TYPE_UPTO,
						getString(R.string.minSpeeding) + getString(R.string.check_input_legal), false);
				return false;
			} else if (!S.isNumber(collectInterval)) {
				EffectManager.getInstance().ttsPlay(
						EffectManager.TTS_TYPE_UPTO,
						getString(R.string.collectInterval) + getString(R.string.check_input_legal)
								+ getString(R.string.not0), false);
				return false;
			} else if (!S.isNumber(sendInterval)) {
				EffectManager.getInstance().ttsPlay(
						EffectManager.TTS_TYPE_UPTO,
						getString(R.string.sendInterval) + getString(R.string.check_input_legal)
								+ getString(R.string.not0), false);
				return false;
			} else {
				saveData(maxspeeding, minspeeding, collectInterval,
						sendInterval);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return true;
	}

	private void saveData(String _sMaxSpeed, String _sMinSpeed,
			String _sCollectInterval, String _sSendInterval) {
		if (DataBaseManager.getInstance().insert(ParameterModel.T_GPS_INFO,
				ParameterModel.MAXSPEEDING, _sMaxSpeed)) {
			EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_UPTO,
					getString(R.string.saveGPS), false);
		}
		DataBaseManager.getInstance().insert(ParameterModel.T_GPS_INFO,
				ParameterModel.MINSPEEDING, _sMinSpeed);
		DataBaseManager.getInstance().insert(ParameterModel.T_GPS_INFO,
				ParameterModel.COLLECT_INTERVAL, _sCollectInterval);
		DataBaseManager.getInstance().insert(ParameterModel.T_GPS_INFO,
				ParameterModel.SEND_INTERVAL, _sSendInterval);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.layout_gpssys:
			startActivity(new Intent(
					android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
			break;
		}
	}

	@Override
	public void finish() {
		// TODO Auto-generated method stub
		if (!save()) {
			return;
		}
		super.finish();
	}

	/** 检测GPS状态 */
	private boolean isGPSEnable() {
		String str = Settings.Secure.getString(getContentResolver(),
				Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
		if (str != null) {
			return str.contains("gps");
		} else {
			return false;
		}
	}
}
